package com.ffapp.demo.user;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.ffapp.demo.R;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.UserBaseInfoUpdateCache;
import com.ffapp.demo.bean.WarnMapListBean;
import com.ffapp.demo.greendao.GreenDaoUtils;
import com.flyco.dialog.widget.NormalDialog;
import com.qmuiteam.qmui.widget.QMUIProgressBar;


import org.greenrobot.eventbus.EventBus;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import my.DialogUtils;
import my.LogUtil;
import my.StringUtil;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;


/**
 * @作者 fourfaith
 * @备注 新闻详情图片查看activity发、
 */
public class UpdateBaseInfoDialog extends NormalDialog {

	public static void toBaseInfoUpdateDialog(Activity mContext,UserBaseInfoUpdateCache updateInfo){
	    if(updateInfo == null){
	        updateInfo = new UserBaseInfoUpdateCache();
            updateInfo.setForceUpdate(true);
        }
		new UpdateBaseInfoDialog(mContext,updateInfo).show();
	}


	@BindView(R.id.progress_bar)
	QMUIProgressBar progress_bar;
	@BindView(R.id.text_message)
	TextView text_message;
	@BindView(R.id.text_percent)
	TextView text_percent;
	@BindView(R.id.text_total_current)
	TextView text_total_current;
	Activity mContext;

	int updatedCount = 0;
	int current_total = 100;
	String currentUpdate;



	UserBaseInfoUpdateCache updateInfo;
//	 UserBaseInfoUpdateCache updateInfoOld;

	public UpdateBaseInfoDialog(Activity context, UserBaseInfoUpdateCache updateInfo) {
		super(context);
		mContext = context;
		this.updateInfo = updateInfo;
		setCancelable(false);
		setCanceledOnTouchOutside(false);
	}

	@Override
	public View onCreateView() {
//        return super.onCreateView();
		View inflate = LayoutInflater.from(mContext).inflate(R.layout.user_update_baseinfo_dialog, null);
		ButterKnife.bind(this, inflate);
		widthScale(0.8f);
		return inflate;
	}

	@Override
	public void setUiBeforShow() {
		initViews();
		initData();
	}

	private void initViews() {

	}

	private void initData() {
//		updateInfoOld = UserBaseInfoUpdateCache.getFromCache();
		updateBaseInfoData();
	}

	@SuppressLint("StaticFieldLeak")
	public  void updateBaseInfoData() {
		new AsyncTask<String, Integer, String>() {
			@Override
			protected String doInBackground(String... strings) {

//				MyParams params = new MyParams();
//				if (updateInfo.isNeedUpdateUser()) {
//					currentUpdate = "正在下载通讯录基础数据";
//					current_total = updateInfo.getUserCount();
//					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
//					mHandler.sendEmptyMessageDelayed(MESSAGE_CONTACT_FAKE_PROGRESS,2000);
//				params.put("showAll", "false");
//					MyHttpUtils.postExcute(Constants.URL_USER_CONTACT, params, new MyHttpListener() {
//								@Override
//								public void onSuccess(int httpWhat, Object result) {
//									ContactListBean mListBeanOrg = (ContactListBean) result;
//									mListBeanOrg.save();
//                                    current_total = updateInfo.getUserCount();
//									updatedCount = updateInfo.getUserCount();
//									updateInfo.setUserCount(updateInfo.getUserCount());
//									updateInfo.setUserCountUpdated(updateInfo.getUserCount());
//									updateInfo.setUserTime(new Date().getTime());
//									mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
////									updateCacheFinal.setUserCacheTime(new Date().getTime());
//								}
//
//								@Override
//								public void onFailure(int httpWhat, Object result) {
////                                super.onFailure(httpWhat, result);
//									LogUtil.i("获取通讯录失败");
//								}
//
//								@Override
//								public void onFinish(int httpWhat) {
//								}
//							},
//							0, ContactListBean.class);
//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_USER,new Date().getTime());
//				} else {
//				}
				updateInfo.setUserTime(new Date().getTime());


				if (updateInfo.isNeedUpdateStation()) {
					currentUpdate = "正在下载微型消防站基础数据";
					updatedCount = 0;
					current_total = updateInfo.getStationCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);

					mListBean = new WarnMapListBean();
					getList(GreenDaoUtils.TYPE_STATION);

//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_STATION,new Date().getTime());
				} else {
				}

				if (updateInfo.isNeedUpdateUnit()) {
					currentUpdate = "正在下载单位信息基础数据";
					updatedCount = 0;
					current_total = updateInfo.getUnitCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);

					mListBean = new WarnMapListBean();
					getList(GreenDaoUtils.TYPE_UNIT);

//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_UNIT,new Date().getTime());
				} else {
				}

				if (updateInfo.isNeedUpdateBuilding()) {
					currentUpdate = "正在下载建筑信息基础数据";
					updatedCount = 0;
					current_total = updateInfo.getBuildingCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					mListBean = new WarnMapListBean();
					getList(GreenDaoUtils.TYPE_BUILDING);
//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_BUILDING,new Date().getTime());
				} else {
				}

				if (updateInfo.isNeedUpdateTrain()) {
					currentUpdate = "正在下载单位演练基础数据";
					updatedCount = 0;
					current_total = updateInfo.getTrainCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					mListBean = new WarnMapListBean();
					getList(GreenDaoUtils.TYPE_TRAIN);
//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_TRAIN,new Date().getTime());
				} else {
				}

				if (updateInfo.isNeedUpdateRisk()) {
					currentUpdate = "正在下载单位隐患基础数据";
					updatedCount = 0;
					current_total = updateInfo.getRiskCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					mListBean = new WarnMapListBean();
					getList(GreenDaoUtils.TYPE_RISK);
//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_RISK,new Date().getTime());
				} else {
				}

				if (updateInfo.isNeedUpdateWater()) {
					currentUpdate = "正在下载水源基础数据";
					updatedCount = 0;
					current_total = updateInfo.getWaterCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);

					mListBean = new WarnMapListBean();
					getList(GreenDaoUtils.TYPE_WATER);
//					updateInfo.setLastUpdateTimeByType(GreenDaoUtils.TYPE_WATER,new Date().getTime());
				} else {
				}

				LogUtil.i("同步本地信息结束----?" + (UserBaseInfoUpdateCache.getFromCache() == null));
				LogUtil.i("同步本地信息结束");
				return null;
			}

			@Override
			protected void onPostExecute(String s) {
				super.onPostExecute(s);
//				updateInfo.setLastCacheUpdateTime(new Date().getTime());
				updateInfo.save();
				currentUpdate = "下载信息完成";
				mHandler.sendEmptyMessage(MESSAGE_UPDATED_FINISH);
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
		}.execute("");

	}

	WarnMapListBean mListBean;
	String current_map_type;
	public void getList(String type){
		current_map_type = type;
		String url = Constants.URL_USER_BASEINFO_WATER;
		MyParams params = new MyParams();
		params.put("pageNum",mListBean.getNextPage());
//		params.put("pageSize", BaseListBeanXF.PAGE_SIZE);
		params.put("pageSize", 800);
		if(!updateInfo.isForceUpdate()){
			params.put("beginTime",updateInfo == null ?"": TimeUtils.getTimeLongToStrByFormat(updateInfo.getLastUpdateTimeByType(type),"yyyy-MM-dd HH:mm:ss"));
		}
		switch (type){
			case GreenDaoUtils.TYPE_WATER:
				url = Constants.URL_USER_BASEINFO_WATER;
				break;
			case GreenDaoUtils.TYPE_STATION:
				url = Constants.URL_USER_BASEINFO_MINI_FIRE_STATION;
				break;
			case GreenDaoUtils.TYPE_UNIT:
				url = Constants.URL_USER_BASEINFO_KEY_UNIT;
				break;
			case GreenDaoUtils.TYPE_BUILDING:
				url = Constants.URL_USER_BASEINFO_BUILDING;
				break;
			case GreenDaoUtils.TYPE_TRAIN:
				url = Constants.URL_USER_BASEINFO_TRAIN;
				break;
			case GreenDaoUtils.TYPE_RISK:
				url = Constants.URL_USER_BASEINFO_RISK;
				break;
		}
		MyHttpUtils.postExcute(url, params, new MyHttpListener() {
					@Override
					public void onSuccess(int httpWhat, Object result) {
						WarnMapListBean listBean = (WarnMapListBean) result;
//						for (WarnMapData mapData : listBean.getList()) {
//							mapData.setMap_type(type);
//						}
						mListBean.addListBean(listBean);
//						if(current_total == 0){
							current_total = mListBean.getTotal();
//						}
//						if(updateInfo.isForceUpdate()){
							updateInfo.setUpdateCountByType(type,current_total);
//						}
						GreenDaoUtils.WarnMapDataInsertData(listBean,type,mCallBack);
//						LogUtil.i(""+currentUpdate+"----->"+mListBean.hasNextPage());
						if(mListBean.hasNextPage()){
							updateInfo.setUpdatedCountByMaptype(type,mListBean.getList().size());
							getList(type);
						}else {
							updateInfo.setUpdatedCountByMaptype(type,mListBean.getTotal());
							updateInfo.setLastUpdateTimeByType(type,new Date().getTime());
							LogUtil.i("下载完后----type--》"+type+GreenDaoUtils.getListBeanCountByType(type));
						}
					}

					@Override
					public void onFailure(int httpWhat, Object result) {
						LogUtil.i("获取消防站信息失败");
					}

					@Override
					public void onFinish(int httpWhat) {
					}
				},
				0, WarnMapListBean.class);
	}

	GreenDaoUtils.GreenDaoInserCallBack mCallBack = new GreenDaoUtils.GreenDaoInserCallBack() {
		@Override
		public void onDataInsert(int count) {
//			updatedCount++;
			updatedCount+= count;
			mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
//			if(updatedCount%50 == 0){
//				mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
//			}
		}
	};

	public static final int MESSAGE_UPDATED_COUNT = 11;
	public static final int MESSAGE_UPDATED_FINISH = 12;
	public static final int MESSAGE_CONTACT_FAKE_PROGRESS = 13;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case MESSAGE_UPDATED_COUNT:
					updateProgressView();
					break;
				case MESSAGE_UPDATED_FINISH:
					StringBuilder builder = new StringBuilder();
					if(updateInfo.isUpdateSuccess()){
//						updateInfo.setLastCacheUpdateTime(new Date().getTime());
//						updateInfo.save();
//						if(updateInfo.isNeedUpdateUser()){
//							builder.append("通讯录共更新了").append(updateInfo.getUserCountUpdated()).append("条，失败").append(updateInfo.getUserCount()-updateInfo.getUserCountUpdated()).append("条。\n");
//						}
						if(updateInfo.isNeedUpdateRisk()){
							builder.append("单位隐患共更新了").append(updateInfo.getRiskCountUpdated()).append("条，失败").append(updateInfo.getRiskCount()-updateInfo.getRiskCountUpdated()).append("条。\n");
						}
						if(updateInfo.isNeedUpdateTrain()){
							builder.append("单位演练共更新了").append(updateInfo.getTrainCountUpdated()).append("条，失败").append(updateInfo.getTrainCount()-updateInfo.getTrainCountUpdated()).append("条。\n");
						}
						if(updateInfo.isNeedUpdateBuilding()){
							builder.append("建筑信息共更新了").append(updateInfo.getBuildingCountUpdated()).append("条，失败").append(updateInfo.getBuildingCount()-updateInfo.getBuildingCountUpdated()).append("条。\n");
						}
						if(updateInfo.isNeedUpdateUnit()){
							builder.append("单位信息共更新了").append(updateInfo.getUnitCountUpdated()).append("条，失败").append(updateInfo.getUnitCount()-updateInfo.getUnitCountUpdated()).append("条。\n");
						}
						if(updateInfo.isNeedUpdateWater()){
							builder.append("水源管理共更新了").append(updateInfo.getWaterCountUpdated()).append("条，失败").append(updateInfo.getWaterCount()-updateInfo.getWaterCountUpdated()).append("条。\n");
						}
						if(updateInfo.isNeedUpdateStation()){
							builder.append("微型消防站共更新了").append(updateInfo.getStationCountUpdated()).append("条，失败").append(updateInfo.getStationCount()-updateInfo.getStationCountUpdated()).append("条。\n");
						}

						EventBus.getDefault().post(new GreenDaoUtils.EventDateChange(GreenDaoUtils.EventDateChange.TYPE_ALL));
					}else {
						builder.append("更新失败");
					}
					DialogUtils.DialogOkMsg(mContext,builder.toString());
					dismiss();
					break;
				case MESSAGE_CONTACT_FAKE_PROGRESS:
					if(mContext == null || mContext.isFinishing())return;
					if(TextUtils.isEmpty(currentUpdate))return;
					if(!currentUpdate.equals("正在下载通讯录基础数据"))return;
					if(updatedCount >= (current_total-10) )return;
						updateProgressView();
					updatedCount += 10;
					mHandler.sendEmptyMessageDelayed(MESSAGE_CONTACT_FAKE_PROGRESS,2000);
					break;
			}

		}
	};



	void updateProgressView(){
//		LogUtil.i("updateProgressView------updatedCount-->"+updatedCount);
//		LogUtil.i("updateProgressView---current_total-->"+current_total);
		if(current_total == 0){
			current_total = 20000;
		}else {

			if(updatedCount >= current_total){
				updatedCount = current_total-1;
			}
		}
		progress_bar.setMaxValue(current_total);
		boolean animated = updatedCount > progress_bar.getProgress();
		progress_bar.setProgress(updatedCount,animated);
		text_message.setText(currentUpdate);
		text_total_current.setText(updatedCount+"/"+current_total);
		text_percent.setText(StringUtil.getPercent(updatedCount,current_total));
	}

}
